package com.xcf.controller.system.login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xcf.controller.base.BaseController;
import com.xcf.entity.system.Menu;
import com.xcf.entity.system.Role;
import com.xcf.entity.system.User;
import com.xcf.service.business.bookingcargo.HomePageService;
import com.xcf.service.system.appuser.AppuserManager;
import com.xcf.service.system.buttonrights.ButtonrightsManager;
import com.xcf.service.system.menu.MenuManager;
import com.xcf.service.system.role.RoleManager;
import com.xcf.service.system.user.UserManager;
import com.xcf.service.system.xcfbutton.XCFbuttonManager;
import com.xcf.service.xcfoa.datajur.DatajurManager;
import com.xcf.util.AppUtil;
import com.xcf.util.Const;
import com.xcf.util.DateUtil;
import com.xcf.util.Jurisdiction;
import com.xcf.util.PageData;
import com.xcf.util.RightsHelper;
import com.xcf.util.Tools;

import cn.com.xcf.spring.AppContextConfig;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 总入口
 *
 * @author Micro Chen
 *         修改日期：2017/09/20
 */

@Controller
@RequestMapping(value = "/")
public class LoginController extends BaseController {

    @Resource(name = "userService")
    private UserManager userService;
    @Resource(name = "menuService")
    private MenuManager menuService;
    @Resource(name = "roleService")
    private RoleManager roleService;
    @Resource(name = "buttonrightsService")
    private ButtonrightsManager buttonrightsService;
    @Resource(name = "xcfbuttonService")
    private XCFbuttonManager xcfbuttonService;
    @Resource(name = "appuserService")
    private AppuserManager appuserService;
    @Resource(name = "datajurService")
    private DatajurManager datajurService;
    @Resource
    private HomePageService homePageService;

    /**
     * 访问登录页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login_toLogin")
    public ModelAndView toLogin() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
        mv.setViewName("system/index/login");
        mv.addObject("pd", pd);
        return mv;
    }

    private boolean validateLogin(String sessionCode,String code){
        if(!AppContextConfig.getBoolean("user.login.code.validate",true)){
            return true;
        }
        return Tools.notEmpty(sessionCode) && sessionCode.equalsIgnoreCase(code);
    }
    /**
     * 请求登录，验证用户
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login_login", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object login() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        PageData pd = new PageData();
        pd = this.getPageData();
        String errInfo = "";
        String KEYDATA[] = pd.getString("KEYDATA").replaceAll("qq313596790xcf", "").replaceAll("QQ978336446xcf", "").split(",xcf,");
        if (null != KEYDATA && KEYDATA.length == 3) {
            Session session = Jurisdiction.getSession();
            String sessionCode = (String) session.getAttribute(Const.SESSION_SECURITY_CODE);        //获取session中的验证码
            String code = KEYDATA[2];
            if (null == code || "".equals(code)) {//判断效验码
                errInfo = "nullcode";            //效验码为空
            } else {
                try {
                    String USERNAME = KEYDATA[0];    //登录过来的用户名
                    String PASSWORD = KEYDATA[1];    //登录过来的密码
                    pd.put("USERNAME", USERNAME);
                    if (validateLogin(sessionCode,code)) {        //判断登录验证码
                        String passwd = new SimpleHash("SHA-1", USERNAME, PASSWORD).toString();    //密码加密
                        pd.put("PASSWORD", passwd);
                        pd = userService.getUserByNameAndPwd(pd);    //根据用户名和密码去读取用户信息
                        if (pd != null) {
                            pd.put("LAST_LOGIN", DateUtil.getTime().toString());
                            userService.updateLastLogin(pd);
                            User user = new User();
                            user.setUSER_ID(pd.getString("USER_ID"));
                            user.setUSERNAME(pd.getString("USERNAME"));
                            user.setPASSWORD(pd.getString("PASSWORD"));
                            user.setNAME(pd.getString("NAME"));
                            user.setRIGHTS(pd.getString("RIGHTS"));
                            user.setROLE_ID(pd.getString("ROLE_ID"));
                            user.setLAST_LOGIN(pd.getString("LAST_LOGIN"));
                            user.setIP(pd.getString("IP"));
                            user.setSTATUS(pd.getString("STATUS"));
                            session.setAttribute(Const.SESSION_USER, user);            //把用户信息放session中
                            session.removeAttribute(Const.SESSION_SECURITY_CODE);    //清除登录验证码的session
                            //shiro加入身份验证
                            Subject subject = SecurityUtils.getSubject();
                            UsernamePasswordToken token = new UsernamePasswordToken(USERNAME, PASSWORD);
                            try {
                                subject.login(token);
                            } catch (AuthenticationException e) {
                                errInfo = "身份验证失败！";
                            }
                        } else {
                            errInfo = "usererror";                //用户名或密码有误
                            logBefore(logger, USERNAME + "登录系统密码或用户名错误");
                        }
                    } else {
                        errInfo = "codeerror";                    //验证码输入有误
                    }
                    if (Tools.isEmpty(errInfo)) {
                        errInfo = "success";                    //验证成功
                        logBefore(logger, USERNAME + "登录系统");
                    }
                } catch (Exception ex) {
                    logger.error(ex);
                }
            }
        } else {
            errInfo = "error";    //缺少参数
        }
        map.put("result", errInfo);
        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * 访问系统首页
     *
     * @param changeMenu：切换菜单参数
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/main/{changeMenu}")
    public ModelAndView login_index(@PathVariable("changeMenu") String changeMenu) throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            Session session = Jurisdiction.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);                        //读取session中的用户信息(单独用户信息)
            if (user != null) {
                User userr = (User) session.getAttribute(Const.SESSION_USERROL);                //读取session中的用户信息(含角色信息)
                if (null == userr) {
                    user = userService.getUserAndRoleById(user.getUSER_ID());                //通过用户ID读取用户信息和角色信息
                    session.setAttribute(Const.SESSION_USERROL, user);                        //存入session
                } else {
                    user = userr;
                }
                String USERNAME = user.getUSERNAME();
                Role role = user.getRole();                                                    //获取用户角色
                String roleRights = role != null ? role.getRIGHTS() : "";                        //角色权限(菜单权限)
                session.setAttribute(USERNAME + Const.SESSION_ROLE_RIGHTS, roleRights);    //将角色权限存入session
                session.setAttribute(Const.SESSION_USERNAME, USERNAME);                        //放入用户名到session
                this.setAttributeToAllDEPARTMENT_ID(session, USERNAME);                        //把用户的组织机构权限放到session里面
                List<Menu> allmenuList = new ArrayList<Menu>();
                allmenuList = this.getAttributeMenu(session, USERNAME, roleRights);            //菜单缓存
                List<Menu> menuList = new ArrayList<Menu>();
                menuList = this.changeMenuF(allmenuList, session, USERNAME, changeMenu);    //切换菜单
                if (null == session.getAttribute(USERNAME + Const.SESSION_QX)) {
                    session.setAttribute(USERNAME + Const.SESSION_QX, this.getUQX(USERNAME));//按钮权限放到session中
                }
                this.getRemortIP(USERNAME);    //更新登录IP
                mv.setViewName("system/index/main");
                mv.addObject("user", user);
                mv.addObject("menuList", menuList);
            } else {
                mv.setViewName("system/index/login");//session失效后跳转登录页面
            }
        } catch (Exception e) {
            mv.setViewName("system/index/login");
            logger.error(e.getMessage(), e);
        }
        pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
        PageData num = homePageService.CountBookingNote();
        pd.put("NUM", num.get("NUM"));
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 菜单缓存
     *
     * @param session
     * @param USERNAME
     * @param roleRights
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<Menu> getAttributeMenu(Session session, String USERNAME, String roleRights) throws Exception {
        List<Menu> allmenuList = new ArrayList<Menu>();
        if (null == session.getAttribute(USERNAME + Const.SESSION_allmenuList)) {
            allmenuList = menuService.listAllMenuQx("0");                            //获取所有菜单
            if (Tools.notEmpty(roleRights)) {
                allmenuList = this.readMenu(allmenuList, roleRights);                //根据角色权限获取本权限的菜单列表
            }
            session.setAttribute(USERNAME + Const.SESSION_allmenuList, allmenuList);//菜单权限放入session中
        } else {
            allmenuList = (List<Menu>) session.getAttribute(USERNAME + Const.SESSION_allmenuList);
        }
        return allmenuList;
    }

    /**
     * 根据角色权限获取本权限的菜单列表(递归处理)
     *
     * @param menuList：传入的总菜单
     * @param roleRights：加密的权限字符串
     * @return
     */
    public List<Menu> readMenu(List<Menu> menuList, String roleRights) {
        for (int i = 0; i < menuList.size(); i++) {
            menuList.get(i).setHasMenu(RightsHelper.testRights(roleRights, menuList.get(i).getMENU_ID()));
            if (menuList.get(i).isHasMenu()) {        //判断是否有此菜单权限
                this.readMenu(menuList.get(i).getSubMenu(), roleRights);//是：继续排查其子菜单
            }
        }
        return menuList;
    }

    /**
     * 切换菜单处理
     *
     * @param allmenuList
     * @param session
     * @param USERNAME
     * @param changeMenu
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Menu> changeMenuF(List<Menu> allmenuList, Session session, String USERNAME, String changeMenu) {
        List<Menu> menuList = new ArrayList<Menu>();
        if (null == session.getAttribute(USERNAME + Const.SESSION_menuList) || ("yes".equals(changeMenu))) {
            List<Menu> menuList1 = new ArrayList<Menu>();
            List<Menu> menuList2 = new ArrayList<Menu>();
            for (int i = 0; i < allmenuList.size(); i++) {//拆分菜单
                Menu menu = allmenuList.get(i);
                if ("1".equals(menu.getMENU_TYPE())) {
                    menuList1.add(menu);
                } else {
                    menuList2.add(menu);
                }
            }
            session.removeAttribute(USERNAME + Const.SESSION_menuList);
            if ("2".equals(session.getAttribute("changeMenu"))) {
                session.setAttribute(USERNAME + Const.SESSION_menuList, menuList1);
                session.removeAttribute("changeMenu");
                session.setAttribute("changeMenu", "1");
                menuList = menuList1;
            } else {
                session.setAttribute(USERNAME + Const.SESSION_menuList, menuList2);
                session.removeAttribute("changeMenu");
                session.setAttribute("changeMenu", "2");
                menuList = menuList2;
            }
        } else {
            menuList = (List<Menu>) session.getAttribute(USERNAME + Const.SESSION_menuList);
        }
        return menuList;
    }

    /**
     * 把用户的组织机构权限放到session里面
     *
     * @param session
     * @param USERNAME
     * @return
     * @throws Exception
     */
    public void setAttributeToAllDEPARTMENT_ID(Session session, String USERNAME) throws Exception {
        String DEPARTMENT_IDS = "0", DEPARTMENT_ID = "0";
        if (!"admin".equals(USERNAME)) {
            PageData pd = datajurService.getDEPARTMENT_IDS(USERNAME);
            DEPARTMENT_IDS = null == pd ? "无权" : pd.getString("DEPARTMENT_IDS");
            DEPARTMENT_ID = null == pd ? "无权" : pd.getString("DEPARTMENT_ID");
        }
        session.setAttribute(Const.DEPARTMENT_IDS, DEPARTMENT_IDS);    //把用户的组织机构权限集合放到session里面
        session.setAttribute(Const.DEPARTMENT_ID, DEPARTMENT_ID);    //把用户的最高组织机构权限放到session里面
    }

    /**
     * 进入tab标签
     *
     * @return
     */
    @RequestMapping(value = "/tab")
    public String tab() {
        return "system/index/tab";
    }

    /**
     * 进入首页后的默认页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login_default")
    public ModelAndView defaultPage() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd.put("userCount", Integer.parseInt(userService.getUserCount("").get("userCount").toString()) - 1);                //系统用户数
        pd.put("appUserCount", Integer.parseInt(appuserService.getAppUserCount("").get("appUserCount").toString()));    //会员数
        mv.addObject("pd", pd);
        mv.setViewName("system/index/default");
        return mv;
    }
//    /**
//     * 首页
//     * @param page
//     * @return
//     * @throws Exception
//     */
//    @SuppressWarnings({ "rawtypes", "unchecked" })
//	@RequestMapping(value="/findHomePageInfo")
//    @ResponseBody
//    public ResponseResult list() throws Exception{
////		PageHelper.startPage(page, 35);
////    	PageData pd = new PageData();
//		List<Map> list = homePageService.queryByPage(null);
//		return ResponseResult.success(new PageInfo(list));
//	}
    /**
     * 首页信息
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/findHomePageInfo")
    public void homePageInfo(HttpServletResponse response)throws Exception{
    	PageData p = new PageData();
    	p = this.getPageData();
    	List<PageData> homePage = homePageService.findHomePageInfo(p);
    	JSONArray json = new JSONArray();
    	for(PageData pd : homePage){
    		JSONObject jb = new JSONObject();
    		
    		jb.put("ID", pd.get("ID"));
    		if(pd.get("BILL_CODE")!=null &&pd.get("BILL_CODE")!=""){
    			jb.put("BILL_CODE", pd.getString("BILL_CODE"));
    		}
    		if(pd.get("LADING_BILL_CODE")!=null &&pd.get("LADING_BILL_CODE")!=""){
    			jb.put("LADING_BILL_CODE", pd.getString("LADING_BILL_CODE"));
    		}
    		if(pd.get("TRADE_METHOD")!=null &&pd.get("TRADE_METHOD")!=""){
    			jb.put("TRADE_METHOD", pd.getString("TRADE_METHOD"));
    		}
    		if(pd.get("SEA_UNLOAD")!=null &&pd.get("SEA_UNLOAD")!=""){
    			jb.put("SEA_UNLOAD", pd.getString("SEA_UNLOAD"));
    		}
    		if(pd.get("CARRIER")!=null &&pd.get("CARRIER")!=""){
    			jb.put("CARRIER", pd.getString("CARRIER"));
    		}
    		if(pd.get("SHIP_COMPANY")!=null &&pd.get("SHIP_COMPANY")!=""){
    			jb.put("SHIP_COMPANY", pd.getString("SHIP_COMPANY"));
    		}
    		if(pd.get("BOAT_NAME")!=null &&pd.get("BOAT_NAME")!=""){
    			jb.put("BOAT_NAME", pd.getString("BOAT_NAME"));
    		}
    		if(pd.get("BOAT_VOYAGE_NAME")!=null &&pd.get("BOAT_VOYAGE_NAME")!=""){
    			jb.put("BOAT_VOYAGE_NAME", pd.getString("BOAT_VOYAGE_NAME"));
    		}
    		if(pd.get("SHIPPER_NAME")!=null &&pd.get("SHIPPER_NAME")!=""){
    			jb.put("SHIPPER_NAME", pd.getString("SHIPPER_NAME"));
    		}
    		if(pd.get("STARTING_PLACE")!=null &&pd.get("STARTING_PLACE")!=""){
    			jb.put("STARTING_PLACE", pd.getString("STARTING_PLACE"));
    		}
    		if(pd.get("DESTINATION")!=null &&pd.get("DESTINATION")!=""){
    			jb.put("DESTINATION", pd.getString("DESTINATION"));
    		}
    		if(pd.get("CHINESE_NAME")!=null &&pd.get("CHINESE_NAME")!=""){
    			jb.put("CHINESE_NAME", pd.getString("CHINESE_NAME"));
    		}
    		if(pd.get("SALER_NAME")!=null &&pd.get("SALER_NAME")!=""){
    			jb.put("SALER_NAME", pd.getString("SALER_NAME"));
    		}
    		if(pd.get("BILL_INPUTER")!=null &&pd.get("BILL_INPUTER")!=""){
    			jb.put("BILL_INPUTER", pd.getString("BILL_INPUTER"));
    		}
    		if(pd.get("SHIP_REGION")!=null &&pd.get("SHIP_REGION")!=""){
    			jb.put("SHIP_REGION", pd.getString("SHIP_REGION"));
    		}
    		if(pd.get("SCHEDULED_SAILING_TIME")!=null &&pd.get("SCHEDULED_SAILING_TIME")!=""){
//    			SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd HH:mm:ss"); 
//    	        Date d=format.parse(pd.get("SCHEDULED_SAILING_TIME").toString());
    			jb.put("SCHEDULED_SAILING_TIME", pd.get("SCHEDULED_SAILING_TIME").toString());
    		}
    		if(pd.get("PLANNED_ARRIVAL_TIME")!=null &&pd.get("PLANNED_ARRIVAL_TIME")!=""){
//    			SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd HH:mm:ss"); 
//    	        Date d=format.parse(pd.get("PLANNED_ARRIVAL_TIME").toString());
    			jb.put("PLANNED_ARRIVAL_TIME", pd.get("PLANNED_ARRIVAL_TIME").toString());
    		}
    		if(pd.get("SHIP_NAME")!=null &&pd.get("SHIP_NAME")!=""){
    			jb.put("SHIP_NAME", pd.getString("SHIP_NAME"));
    		}
    		if(pd.get("SHIP_VOYAGE_NAME")!=null &&pd.get("SHIP_VOYAGE_NAME")!=""){
    			jb.put("SHIP_VOYAGE_NAME", pd.getString("SHIP_VOYAGE_NAME"));
    		}
    		if(pd.get("SHIP_ETD")!=null &&pd.get("SHIP_ETD")!=""){
//    			SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd HH:mm:ss"); 
//    	        Date d=format.parse(pd.get("SHIP_ETD").toString());
    			jb.put("SHIP_ETD", pd.get("SHIP_ETD").toString());
    		}
    		if(pd.get("ENCASEMENT_METHOD")!=null &&pd.get("ENCASEMENT_METHOD")!=""){
    			jb.put("ENCASEMENT_METHOD", pd.getString("ENCASEMENT_METHOD"));
    		}
    		if(pd.get("ESTIMATE_EXTRACT_BOX_TIME")!=null &&pd.get("ESTIMATE_EXTRACT_BOX_TIME")!=""){
//    			SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd HH:mm:ss"); 
//    	        Date d=format.parse(pd.get("ESTIMATE_EXTRACT_BOX_TIME").toString());
    			jb.put("ESTIMATE_EXTRACT_BOX_TIME",pd.get("ESTIMATE_EXTRACT_BOX_TIME").toString());
    		}
    		if(pd.get("WEIGHT_BOX_TIME")!=null &&pd.get("WEIGHT_BOX_TIME")!=""){
//    			SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd HH:mm:ss"); 
//    	        Date d=format.parse(pd.get("WEIGHT_BOX_TIME").toString());
    			jb.put("WEIGHT_BOX_TIME",pd.get("WEIGHT_BOX_TIME").toString());
    		}
    		if(pd.get("IS_CUSTOM_INFO_ARRIVE")!=null &&pd.get("IS_CUSTOM_INFO_ARRIVE")!=""){
    			jb.put("IS_CUSTOM_INFO_ARRIVE", pd.getString("IS_CUSTOM_INFO_ARRIVE"));
    		}
    		if(pd.get("GOODS_NUM")!=null &&pd.get("GOODS_NUM")!=""){
    			jb.put("GOODS_NUM", pd.getString("GOODS_NUM"));
    		}
    		if(pd.get("PACK_TYPE")!=null &&pd.get("PACK_TYPE")!=""){
    			jb.put("PACK_TYPE", pd.getString("PACK_TYPE"));
    		}
    		if(pd.get("GOODS_GROSS_WEIGHT")!=null &&pd.get("GOODS_GROSS_WEIGHT")!=""){
    			jb.put("GOODS_GROSS_WEIGHT", pd.getString("GOODS_GROSS_WEIGHT"));
    		}
    		if(pd.get("VOLUME")!=null &&pd.get("VOLUME")!=""){
    			jb.put("VOLUME", pd.getString("VOLUME"));
    		}
    		
    		json.add(jb);
    	}
    	response.setContentType("text/html; charset=utf-8");
		response.getWriter().write("{"+"\""+"total"+"\""+":"+"\""+"5"+"\""+","+"\""+"root"+"\""+":"+json.toString()+"}");				
		response.getWriter().flush();
    	
    }
    @RequestMapping(value="/ConsoleData")
    @ResponseBody
    public String ConsoleData(HttpServletResponse response) throws Exception{
    	List<Map> list = homePageService.findConsoleData();
    	JSONArray json = new JSONArray();
    	JSONObject jb = new JSONObject();
    	jb.put("total", 10);
    	jb.put("rows", list);
    	json.add(jb);
//    	for(Map p:list){
//    		JSONObject jb = new JSONObject();
//    		jb.put("BILL_CODE", p.get("BILL_CODE"));
//    		jb.put("LADING_BILL_CODE", p.get("LADING_BILL_CODE"));
//    		jb.put("BOAT_ETD", p.get("BOAT_ETD"));
//    		jb.put("dayNumber", p.get("dayNumber"));
    		
//    		
//    	}
    	String json1= json.toString().substring(0,json.toString().length()-1);
    	String json2 = json1.substring(1, json1.length());
    	response.setContentType("text/html; charset=utf-8");
		response.getWriter().write(json2);				
		response.getWriter().flush();
		return null;
    	
//		return ResponseResult.success(new PageInfo(rows));
    }
    /**
     * 用户注销
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout")
    public ModelAndView logout() {
        String USERNAME = Jurisdiction.getUsername();    //当前登录的用户名
        logBefore(logger, USERNAME + "退出系统");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        Session session = Jurisdiction.getSession();    //以下清除session缓存
        session.removeAttribute(Const.SESSION_USER);
        session.removeAttribute(USERNAME + Const.SESSION_ROLE_RIGHTS);
        session.removeAttribute(USERNAME + Const.SESSION_allmenuList);
        session.removeAttribute(USERNAME + Const.SESSION_menuList);
        session.removeAttribute(USERNAME + Const.SESSION_QX);
        session.removeAttribute(Const.SESSION_userpds);
        session.removeAttribute(Const.SESSION_USERNAME);
        session.removeAttribute(Const.SESSION_USERROL);
        session.removeAttribute("changeMenu");
        session.removeAttribute("DEPARTMENT_IDS");
        session.removeAttribute("DEPARTMENT_ID");
        //shiro销毁登录
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        pd = this.getPageData();
        pd.put("msg", pd.getString("msg"));
        pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
        mv.setViewName("system/index/login");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 获取用户权限
     *
     * @param session
     * @return
     */
    public Map<String, String> getUQX(String USERNAME) {
        PageData pd = new PageData();
        Map<String, String> map = new HashMap<String, String>();
        try {
            pd.put(Const.SESSION_USERNAME, USERNAME);
            pd.put("ROLE_ID", userService.findByUsername(pd).get("ROLE_ID").toString());//获取角色ID
            pd = roleService.findObjectById(pd);                                        //获取角色信息
            map.put("adds", pd.getString("ADD_QX"));    //增
            map.put("dels", pd.getString("DEL_QX"));    //删
            map.put("edits", pd.getString("EDIT_QX"));    //改
            map.put("chas", pd.getString("CHA_QX"));    //查
            List<PageData> buttonQXnamelist = new ArrayList<PageData>();
            if ("admin".equals(USERNAME)) {
                buttonQXnamelist = xcfbuttonService.listAll(pd);                    //admin用户拥有所有按钮权限
            } else {
                buttonQXnamelist = buttonrightsService.listAllBrAndQxname(pd);    //此角色拥有的按钮权限标识列表
            }
            for (int i = 0; i < buttonQXnamelist.size(); i++) {
                map.put(buttonQXnamelist.get(i).getString("QX_NAME"), "1");        //按钮权限
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return map;
    }

    /**
     * 更新登录用户的IP
     *
     * @param USERNAME
     * @throws Exception
     */
    public void getRemortIP(String USERNAME) throws Exception {
        PageData pd = new PageData();
        HttpServletRequest request = this.getRequest();
        String ip = "";
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        } else {
            ip = request.getHeader("x-forwarded-for");
        }
        pd.put("USERNAME", USERNAME);
        pd.put("IP", ip);
        userService.saveIP(pd);
    }

}
